package com.live.video.authority.controller;

import com.alibaba.fastjson.JSON;
import com.live.video.authority.service.JWTService;
import com.live.video.authority.util.TokenParseUtil;
import com.live.video.authority.vo.CommonResponseVO;
import com.live.video.authority.vo.JwtToken;
import com.live.video.authority.vo.LoginUserInfo;
import com.live.video.authority.vo.UsernameAndPassword;
import com.live.video.common.annotation.IgnoreResponseAdvice;
import com.live.video.web.entity.Students;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2022-07-26 12:27
 */
@Slf4j
@RestController
public class AuthorityController {

    @Autowired
    private JWTService jwtService;

    @IgnoreResponseAdvice
    @PostMapping("login")
    public CommonResponseVO login(UsernameAndPassword usernameAndPassword) throws Exception {
        log.info("get UsernameAndPassword with param : [{}]", JSON.toJSONString(usernameAndPassword));

        return jwtService.generatorToken(usernameAndPassword.getUsername(), usernameAndPassword.getPassword());
    }

    @IgnoreResponseAdvice
    @PostMapping("registy")
    public CommonResponseVO registy(UsernameAndPassword usernameAndPassword, Students students) throws Exception {
        students.setSpecialtyId(1549582939531005954L);
        log.info("get UsernameAndPassword and student with param : [{}], [{}]", JSON.toJSONString(usernameAndPassword), JSON.toJSONString(students));

        return jwtService.registerUserAndGeneratorToken(usernameAndPassword, students);
    }

    @IgnoreResponseAdvice
    @PostMapping("resetPassword")
    public CommonResponseVO resetPassword(@RequestHeader("Authorization") String token, String newPassword, String oldPassword) throws Exception {
        LoginUserInfo loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
        log.info("get token, newPassword, oldPassword with param : [{}], [{}], [{}],", JSON.toJSONString(loginUserInfo), newPassword, oldPassword);

        return jwtService.resetPassword(loginUserInfo.getUsername(), newPassword, oldPassword);
    }

    @IgnoreResponseAdvice
    @GetMapping("checkToken")
    public int checkToken(String token, String currentTime, Long videoId) throws Exception {
        log.info("get token, currentTime, videoId with param : [{}], [{}], [{}]", token, currentTime, videoId);
        if(token == null){
            return 0;
        }
        LoginUserInfo loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
        if(loginUserInfo == null){
            return 0;
        }
        //TODO 验证当前用户是否有该视频的点播权
        log.info("get tcurrentTime with param : [{}]", new BigDecimal(currentTime).intValue());
        if(new BigDecimal(currentTime).intValue() > 300){
            return 3;
        }

        return 1;
    }
}
